/**
 * 
 */
package freedom.needle.util;

import java.util.HashMap;
import java.util.Map;

import freedom.needle.enums.TaskCommand;

/**
 * @author charlie
 *
 */
public class EnumHelper {
	
	public enum EnumKeyType {
		NAME,ORDINAL,CUSTOM_KEY
	}
	
	public static <E extends Enum<E>> String display(E enumObject, EnumKeyType enumKeyType) {
		String key = null;
		if(enumKeyType == EnumKeyType.CUSTOM_KEY) {
			key = String.valueOf(((EnumDecorate<?>)enumObject).getKey());
		}
		else if(enumKeyType == EnumKeyType.ORDINAL)
				key = String.valueOf(enumObject.ordinal());
		else if(enumKeyType == EnumKeyType.NAME)
			key = enumObject.name();
		String fullKey = enumObject.getClass().getName() + "." + key;
		String displayText = null;
		try {
			displayText = ResourceMessage.getInstance().getMessage(fullKey);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return displayText != null ? displayText : key;
	}
	
	public static <E extends Enum<E>> E acquireEnumObjectByName(Class<E> enumClass, String name) {
		return Enum.valueOf(enumClass, name);
	}
	
	public static <E extends Enum<E>> E acquireEnumObjectByOrdinal(Class<E> enumClass, int ordinal) {
		return enumClass.getEnumConstants()[ordinal];
	}
	
	@SuppressWarnings("unchecked")
	public static <E extends Enum<E>> E acquireEnumObjectByKey(Class<E> enumClass, Object key) {
		if(!map.containsKey(enumClass))
			init(enumClass);
		return (E) map.get(enumClass).get(String.valueOf(key));
	}
	
	private static Map<Class<? extends Enum<?>>, Map<String, ? extends Enum<?>>> map = new HashMap<Class<? extends Enum<?>>, Map<String, ? extends Enum<?>>>();
	
	/**
	 * @param enumClass
	 */
	private synchronized static  <E extends Enum<E>> void init(Class<E> enumClass) {
		Map<String, E> map = new HashMap<String, E>();
		for(E e : enumClass.getEnumConstants()) {
			EnumDecorate<?> ed = (EnumDecorate<?>)e;
			map.put(String.valueOf(ed.getKey()), e);
		}
		EnumHelper.map.put(enumClass, map);
	}


	public static void main(String[] args) {
		String a = TaskCommand.INIT.getDisplayText();
		System.out.println(a);
		Enum<?> b = TaskCommand.INIT.getEnumObject("2");
		System.out.println(b);
		
	}

}
